package com.ruoyi.operation.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.operation.domain.Customer;
import com.ruoyi.operation.domain.SysUserTimesLog;
import com.ruoyi.operation.mapper.CustomerMapper;
import com.ruoyi.operation.mapper.SysUserTimesLogMapper;
import com.ruoyi.system.domain.Report;
import com.ruoyi.system.service.IReportService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/customer")
public class CustomerController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private SysUserTimesLogMapper sysUserTimesLogMapper;

    @Autowired
    private IReportService reportService;

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/info")
    public AjaxResult getInfo()
    {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        Customer customer = customerMapper.getCustomerInfo(userId);
        customer.setUserId(userId);
        return AjaxResult.success(customer);
    }

    @GetMapping("/times/log")
    public TableDataInfo list(SysUserTimesLog sysUserTimesLog)
    {
        startPage();
        Long userId = SecurityUtils.getLoginUser().getUserId();
        sysUserTimesLog.setUserId(userId);
        List<SysUserTimesLog> list = sysUserTimesLogMapper.getLogList(sysUserTimesLog);
        return getDataTable(list);
    }

    @PostMapping("/times/reduce")
    public AjaxResult timesReduce(@RequestBody Report report)
    {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        customerMapper.timesReduce(userId);

        SysUserTimesLog sysUserTimesLog = new SysUserTimesLog();
        sysUserTimesLog.setUserId(userId);
        sysUserTimesLog.setTimes(-1L);
        sysUserTimesLog.setType("output");
        sysUserTimesLog.setRemark("生成报告");
        sysUserTimesLog.setCreateTime(new Date());
        sysUserTimesLog.setUpdateTime(new Date());
        sysUserTimesLogMapper.insertLog(sysUserTimesLog);

        report.setUserId(userId);
        reportService.insertReport(report);

        return AjaxResult.success();
    }
}
